package com.redhat.redwork.widget.dropdown;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
@Service
public class DataModelServiceImpl implements DataModelService {

	private final Log log = LogFactory.getLog(DataModelServiceImpl.class);
	
	// UniversalDao universalDao;
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/*
	 * (non-Javadoc)
	 * @see com.csair.cbd.datamodel.services.DataModelService#loadData(java.lang.String, java.lang.String, java.lang.String)
	 */
	public List<?> loadData(String entityClass, String parentProperty,
			String masterValue) {
		/**
		 * load all the entity from DAO
		 */
		List<?> objects = new ArrayList();
		
		Session session = null;
		try {
			Class<?> clz = Class.forName(entityClass);
			
			session = sessionFactory.openSession();
			Criteria criteria = session.createCriteria(clz);

			if (parentProperty != null) {
				if (sessionFactory.getClassMetadata(clz)
						.getPropertyType(parentProperty) instanceof org.hibernate.type.IntegerType) {
					criteria.add(Restrictions.eq(parentProperty, Integer
							.parseInt(masterValue)));
				} else {
					criteria.add(Restrictions.eq(parentProperty, masterValue));
				}
			}
			objects = criteria.list();
		} catch (Throwable e) {
			log.error(e);
		} finally {
			if(session!=null)
				session.close();
		}

		return objects;
	}

}
